package utils;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import cn.rayland.library.utils.MachineManager;
import cn.rayland.rayland3d.activity.MainActivity;
import cn.rayland.rayland3d.app.App;

/**
 * Created by gw on 2016/5/10.
 */
public class FileServer {
    private static ServerSocket server = null;
    private static ExecutorService mExecutorService = Executors.newCachedThreadPool();

    public static void open(final int port){
        new Thread(){
            @Override
            public void run() {
                try {
                    if(server == null){
                        server = new ServerSocket(port);
                        System.out.println("开启传输服务，端口号："+port+"，等待中。。。");
                        while(true){
                            Socket client = server.accept();
                            System.out.println("客户机IP:"+client.getInetAddress()+" 端口号: "+client.getPort()+" 已连接。。。");
                            mExecutorService.execute(new TransService(client));
                        }
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    public static void close(){
        try {
            if(server!=null){
                server.close();
                server = null;
                System.out.println("传输服务已关闭。。。");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static class TransService implements Runnable{
        private Socket socket;
        private String msg;
        public TransService(Socket socket){
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                DataInputStream dis = new DataInputStream(socket.getInputStream());
                msg = dis.readUTF();
                System.out.println("请求内容为："+msg);
                if(!msg.equals("{\"cmd\":\"getModel\"}")){
                    return;
                }
                File file = new File(App.machineManager.getMachineState().getTask().getTaskName());
                if(file.exists() && file.isFile()){
                    FileInputStream fis = new FileInputStream(file);
                    DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
                    int total = fis.available();
                    dos.writeUTF("{\"name\":\""+file.getName()+"\",\"size\":\""+total+"\"}");
                    byte[] buffer = new byte[1024];
                    int length = -1;
                    int size = 0;
                    System.out.println("开始传输文件："+file.getName());
                    while((length = fis.read(buffer))!=-1){
                        dos.write(buffer,0,length);
                        size += length;
                        System.out.println("当前已传输：" + size + " / " + total);
                    }
                    dos.flush();
                    System.out.println("传输完毕。。。");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
